import React from 'react';
import { View, Button, Image, Input } from '@tarojs/components'
import Taro from '@tarojs/taro';
const avatar = 'https://static3.jekunauto.com/img/others/default_head.png'
import { updateAvatar } from '@/store/user/action'
import { connect } from 'react-redux'
import { AtList, AtListItem, AtToast } from 'taro-ui'
import { getUserDetails, changeUserInfo } from '@/api/user'
import { IS_USERINFO } from '@/store/user/action-types'
import './index.scss'

import CryptoJS from 'crypto-js'

const domain: string = `${BASE_API_URL}`
const getByteLen = (val: any) => {
  let len = 0
  if (!val) {
    len = 0
  } else {
    for (let i = 0; i < val.length; i++) {
      if (String(val[i]).match(/[^\x00-\xff]/gi) !== null) {
        len += 3
      } else {
        len += 1
      }
    }
  }
  return len.toString()
}

interface Toast {
  isOpened: boolean
  status: 'error' | 'loading' | 'success'
  text: string,
}

interface State {
  toast: Toast
  userDetails: GlobalUser.Details | null
}
@connect<any>(({ user }) => ({ user }), dispatch => ({
  changeAvatarUrl(params) {
    dispatch(updateAvatar({ ...this.user.userInfo, ...params }))
  }
}))
class UserInfo extends React.Component<any> {
  constructor (props) {
    super(props)
    this.state = {
      toast: {
        isOpened: false,
        status: 'error',
        text: ''
      },
      userDetails: null
    }
  }
  state: State
  componentDidMount() {
    let { userId } = this.props.user.userInfo
    if (userId) {
      getUserDetails({
        id: userId
      }).then(res => {
        const data = res.data.data
        if (data.userWechatMini) {
          const { avatarurl, nickname } = data.userWechatMini
          if (avatarurl) {
            data.avatarUrl = avatarurl
          }
          if (nickname) {
            data.nickname = nickname
          }
        }

        // const { avatar } = this.props.user.userInfo
        // if (avatar) {
        //   data.avatarUrl = avatar
        // }
        this.setState({
          userDetails: data
        })
      })
    }
  }
  async chooseImage(e: any) {
    console.log(e)
  }

  async getAvatar(e) {
    this.uploadFile(e.detail.avatarUrl)

  }

  getAuth() {
    const USERINFO = Taro.getStorageSync(IS_USERINFO)
    let { accessId, accessKey, serverTime } = USERINFO
    let entityLength: string = '0'
    let clientTime = Date.parse(new Date()['toGMTString']()) / 1000

    if (/^P(OST|UT)$/.test('POST')) {
      entityLength = getByteLen({})
    }

    let clientTimeStamp = typeof clientTime === 'number' ? clientTime : 0
    if (!clientTimeStamp) {
      let date = new Date()['toGMTString']()
      clientTimeStamp = Date.parse(date) / 1000// 客户端时间戳
      clientTime = clientTimeStamp
    }
    let serverTimeStamp = serverTime

    // 时间差的处理
    let difTimestamp = Number(serverTimeStamp) - Number(clientTimeStamp)// 客户端时间与服务器时间差
    let clientCorrectTimeStamp = +new Date() / 1000 + difTimestamp// 当下正确时间戳
    clientTime = new Date(clientCorrectTimeStamp * 1000)['toGMTString']()// 当下正确时间
    let str = 'POST' + '\\n' + 'v1/upload/create' + '\\n' + entityLength + '\\n' + clientTime
    let hash = CryptoJS.HmacSHA1(str, accessKey)
    let sha = hash.toString(CryptoJS.enc.Base64)
    let auth = 'Jekun ' + accessId + ':' + sha
    return {
      'Authorization': auth,
      'Entity-Date': clientTime,
      'Entity-Length': entityLength,
      'str': str,
      'accessKey': accessKey.substring(accessKey.length - 10)
    }
  }

  async uploadFile(filePath) {
    const { userDetails } = this.state
    const obj = await this.getAuth()
    Taro.uploadFile({
      url: domain + `/v1/upload/create?fields=path,id`,
      filePath,
      name: 'file',
      formData: {
        'act': 239,
        'fields': 'path,id',
        'relatedCode': 0
      },
      header: {
        "Content-Type": "multipart/form-data",
        'Authorization': obj['Authorization'],
        'Entity-Date': obj['Entity-Date'],
        'Entity-Length': obj['Entity-Length'],
        // 'str': obj['str'],
        // 'accessKey': obj['accessKey'],
      },
      success: (res) => {
        let data = res.data
        if (data) {
          data = JSON.parse(data)
          userDetails.avatarUrl = data.data.path
          this.setState({
            userDetails
          })
        }

      },
      fail: function (res) {

      }
    });
  }

  inputChange(e) {
    const { userDetails } = this.state
    userDetails.nickname = e.detail.value
    this.setState({ userDetails })
  }

  submit() {
    const { userDetails } = this.state
    let { avatarUrl, nickname } = userDetails
    if (!avatarUrl) {
      Taro.showToast({
        title: "请上传头像",
        icon: "none"
      })
      return
    }
    if (!nickname) {
      Taro.showToast({
        title: "请输入昵称",
        icon: "none"
      })
      return
    }
    Taro.showLoading({
      title: '保存中'
    })
    changeUserInfo({
      avatar: avatarUrl,
      nickname
    }).then(res => {
      Taro.hideLoading()
      Taro.showToast({
        title: "保存成功"
      })
    })
  }

  render() {
    const { userDetails, toast } = this.state
    if (!userDetails) return null
    let { mobile, avatarUrl, nickname } = userDetails
    avatarUrl = avatar
    if (Object.keys(userDetails).includes('mobile')) {
      if (userDetails.avatarUrl) {
        avatarUrl = userDetails.avatarUrl
      }
    }
    return (
      <View className='userinfo'>
        <AtToast onClose={() => {
          this.setState({
            toast: {
              isOpened: false,
              status: 'error',
              text: ''
            }
          })
        }} isOpened={toast.isOpened} text={toast.text} status={toast.status}
        ></AtToast>
        {/* <AtList>
          <AtListItem
            title='头像'
            arrow='right'
            onClick={this.chooseImage.bind(this)}
            className='avatar-wrap'
            extraThumb={avatarUrl}
          />
          <AtListItem hasBorder={false} title='手机号码' extraText={mobile} />
        </AtList> */}
        <View className='item'>
          <View className='label'>手机号</View>
          <View className='value'>{mobile}</View>
        </View>
				{
					process.env.TARO_ENV === 'weapp' ? <Button className='avatar-btn' openType='chooseAvatar' onChooseAvatar={this.getAvatar.bind(this)}>
						<View className='item'>
							<View className='label'>头像</View>
							<Image className='avatar' src={avatarUrl} />
						</View>
					</Button> : null
				}



        <View className='item'>
          <View className='label'>昵称</View>
          <View className='value'>
            <Input type="nickname" value={nickname} onInput={this.inputChange.bind(this)} placeholder="请输入"></Input>
          </View>
        </View>
        <View className='submit' onClick={this.submit.bind(this)}>保存</View>
      </View>
    )
  }
}
export default UserInfo
